<template>
  <!-- Instructions Stage -->
  <div v-if="stage === 'instructions'" class="max-w-2xl mx-auto">
    <transition appear name="fade">
      <Card class="bg-white/90 backdrop-blur-sm border-pink-200 shadow-lg">
        <CardHeader class="text-center pb-8">
          <div
            class="w-16 h-16 bg-gradient-to-br from-pink-600 to-rose-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
          >
            <Heart class="w-8 h-8 text-white" />
          </div>
          <CardTitle class="text-2xl text-slate-800">{{ t('emotionRecognitionTest.title') }}</CardTitle>
          <p class="text-slate-600 mt-2">{{ t('emotionRecognitionTest.description') }}</p>
        </CardHeader>

        <CardContent class="space-y-6">
          <div
            class="bg-gradient-to-r from-pink-50 to-rose-50 rounded-xl p-6 border border-pink-100"
          >
            <h3
              class="font-semibold text-pink-900 mb-4 flex items-center gap-2"
            >
              <Star class="w-5 h-5" />
              {{ t('emotionRecognitionTest.instructionsTitle') }}
            </h3>
            <div class="space-y-3 text-slate-700">
              <div class="flex gap-3">
                <span
                  class="w-6 h-6 bg-pink-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                  >1</span
                >
                <p>{{ t('emotionRecognitionTest.instruction1') }}</p>
              </div>
              <div class="flex gap-3">
                <span
                  class="w-6 h-6 bg-pink-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                  >2</span
                >
                <p>{{ t('emotionRecognitionTest.instruction2') }}</p>
              </div>
              <div class="flex gap-3">
                <span
                  class="w-6 h-6 bg-pink-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                  >3</span
                >
                <p>{{ t('emotionRecognitionTest.instruction3') }}</p>
              </div>
              <div class="flex gap-3">
                <span
                  class="w-6 h-6 bg-pink-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5"
                  >4</span
                >
                <p>{{ t('emotionRecognitionTest.instruction4') }}</p>
              </div>
            </div>
          </div>

          <div class="grid md:grid-cols-2 gap-4">
            <div
              class="bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl p-4 border border-blue-200"
            >
              <h4
                class="font-semibold text-blue-800 mb-2 flex items-center gap-2"
              >
                <Eye class="w-4 h-4" />
                {{ t('emotionRecognitionTest.facialExpressions') }}
              </h4>
              <p class="text-sm text-blue-700">{{ t('emotionRecognitionTest.facialExpressionsDesc') }}</p>
            </div>
            <div
              class="bg-gradient-to-br from-green-50 to-green-100 rounded-xl p-4 border border-green-200"
            >
              <h4
                class="font-semibold text-green-800 mb-2 flex items-center gap-2"
              >
                <Users class="w-4 h-4" />
                {{ t('emotionRecognitionTest.bodyLanguage') }}
              </h4>
              <p class="text-sm text-green-700">{{ t('emotionRecognitionTest.bodyLanguageDesc') }}</p>
            </div>
            <div
              class="bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl p-4 border border-purple-200"
            >
              <h4
                class="font-semibold text-purple-800 mb-2 flex items-center gap-2"
              >
                <Mic class="w-4 h-4" />
                {{ t('emotionRecognitionTest.voiceTone') }}
              </h4>
              <p class="text-sm text-purple-700">{{ t('emotionRecognitionTest.voiceToneDesc') }}</p>
            </div>
            <div
              class="bg-gradient-to-br from-orange-50 to-orange-100 rounded-xl p-4 border border-orange-200"
            >
              <h4
                class="font-semibold text-orange-800 mb-2 flex items-center gap-2"
              >
                <Smile class="w-4 h-4" />
                {{ t('emotionRecognitionTest.socialScenarios') }}
              </h4>
              <p class="text-sm text-orange-700">{{ t('emotionRecognitionTest.socialScenariosDesc') }}</p>
            </div>
          </div>

          <Button
            class="w-full bg-gradient-to-r from-pink-600 to-rose-500 hover:from-pink-700 hover:to-rose-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
            size="lg"
            @click="handleStartTest"
          >
            {{ t('emotionRecognitionTest.startTest') }}
          </Button>
        </CardContent>
      </Card>
    </transition>
  </div>

  <!-- Test Stage -->
  <div
    v-else-if="stage === 'test' && currentStimulusData"
    class="max-w-4xl mx-auto space-y-6"
  >
    <transition name="slide-down">
      <div
        v-if="showFeedback"
        class="fixed top-20 left-1/2 transform -translate-x-1/2 z-50 max-w-sm w-full"
      >
        <Card
          :class="[
            'border-0 shadow-xl',
            feedbackCorrect
              ? 'bg-green-500 text-white'
              : 'bg-red-500 text-white',
          ]"
        >
          <CardContent class="py-4 px-6">
            <div class="text-center">
              <div class="font-semibold mb-2 text-lg">
                {{ feedbackCorrect ? t('emotionRecognitionTest.feedbackCorrect') : t('emotionRecognitionTest.feedbackIncorrect') }}
              </div>
              <div class="text-sm opacity-90">{{ feedbackMessage }}</div>
            </div>
          </CardContent>
        </Card>
      </div>
    </transition>

    <div class="flex flex-col sm:flex-row gap-4 items-center justify-between">
      <div class="flex items-center gap-4 flex-wrap">
        <Badge
          class="bg-pink-100 text-pink-700 border-pink-300"
          variant="outline"
          >{{ t('emotionRecognitionTest.scenario') }} {{ currentStimulus + 1 }} /
          {{ TOTAL_STIMULI }}
        </Badge>
        <Badge :class="stimulusTypeClass" variant="outline">{{
          stimulusTypeDescription
        }}</Badge>
        <Badge :class="stimulusDifficultyClass" variant="outline">{{
          stimulusDifficultyDescription
        }}</Badge>
        <div class="flex items-center gap-2 text-slate-600">
          <Trophy class="w-4 h-4" />
          <span class="font-semibold">{{ score }}</span>
        </div>
      </div>
    </div>

    <Progress :model-value="progress" class="h-2" />

    <Card class="bg-white/90 backdrop-blur-sm border-pink-200 shadow-lg">
      <CardHeader>
        <div class="flex items-center justify-between">
          <CardTitle class="text-lg text-slate-800">{{ t('emotionRecognitionTest.title') }}</CardTitle>
          <Badge
            v-if="currentStimulusData.context"
            class="text-xs"
            variant="secondary"
          >
            {{ t('emotionRecognitionTest.context') }}{{ currentStimulusData.context }}
          </Badge>
        </div>
      </CardHeader>
      <CardContent class="space-y-6">
        <div
          class="bg-gradient-to-r from-slate-50 to-gray-50 rounded-xl p-6 border border-slate-200"
        >
          <p class="text-lg text-slate-800 leading-relaxed text-center">
            {{ currentStimulusData.description }}
          </p>
        </div>
        <div>
          <h4 class="text-md font-semibold text-slate-700 mb-4 text-center">
            {{ t('emotionRecognitionTest.whatEmotion') }}
          </h4>
          <div class="grid grid-cols-2 sm:grid-cols-4 gap-3">
            <div
              v-for="(option, index) in currentStimulusData.options"
              :key="index"
            >
              <Button
                :class="[
                  'w-full h-auto min-h-[3rem] text-center',
                  {
                    'bg-gradient-to-r from-pink-600 to-rose-500 text-white border-pink-600':
                      selectedEmotion === option,
                  },
                ]"
                :variant="selectedEmotion === option ? 'default' : 'outline'"
                @click="handleEmotionSelect(option)"
              >
                <span
                  :class="{
                    'text-white': selectedEmotion === option,
                    'text-slate-800': selectedEmotion !== option,
                  }"
                  >{{ option }}</span
                >
              </Button>
            </div>
          </div>
        </div>
        <div
          v-if="currentStimulusData.intensity"
          class="text-center text-sm text-slate-600"
        >
          {{ t('emotionRecognitionTest.intensityHint') }}{{ intensityDescription }}
        </div>
      </CardContent>
    </Card>
  </div>

  <!-- Confidence Stage -->
  <div v-else-if="stage === 'confidence'" class="max-w-2xl mx-auto space-y-6">
    <transition appear name="fade">
      <Card class="bg-white/90 backdrop-blur-sm border-pink-200 shadow-lg">
        <CardHeader>
          <CardTitle class="text-lg text-slate-800 text-center"
            >{{ t('emotionRecognitionTest.confidenceAssessment') }}</CardTitle
          >
        </CardHeader>
        <CardContent class="space-y-6">
          <div class="text-center">
            <p class="text-slate-700 mb-2">{{ t('emotionRecognitionTest.yourSelectedEmotion') }}</p>
            <div class="text-2xl font-bold text-pink-600 mb-6">
              {{ selectedEmotion }}
            </div>
          </div>
          <div class="space-y-4">
            <p class="text-center text-slate-700">{{ t('emotionRecognitionTest.howConfident') }}</p>
            <div class="px-4">
              <Slider
                :max="5"
                :min="1"
                :model-value="confidence"
                :step="1"
                class="w-full"
                @update:modelValue="(val) => (confidence = val)"
              />
              <div class="flex justify-between mt-2 px-1">
                <div
                  v-for="level in [1, 2, 3, 4, 5]"
                  :key="level"
                  :class="[
                    'text-xs font-semibold transition-colors duration-200',
                    confidence[0] >= level ? 'text-pink-600' : 'text-slate-400',
                  ]"
                >
                  {{ level }}
                </div>
              </div>
              <div class="text-center mt-2">
                <span class="text-sm text-slate-600">{{
                  confidenceDescription
                }}</span>
              </div>
            </div>
          </div>
          <Button
            :disabled="isSubmitting"
            class="w-full bg-gradient-to-r from-pink-600 to-rose-500 hover:from-pink-700 hover:to-rose-600 disabled:from-pink-400 disabled:to-rose-400 text-white py-3 text-lg font-semibold shadow-lg transition-all duration-200"
            size="lg"
            @click="handleConfidenceSubmit"
          >
            <span class="flex items-center gap-2">
              {{ isSubmitting ? t('emotionRecognitionTest.submitting') : t('emotionRecognitionTest.confirmSubmit') }}
              <transition mode="out-in" name="fade">
                <Star v-if="!isSubmitting" class="w-4 h-4" />
                <div v-else class="w-4 h-4 animate-spin"><Star /></div>
              </transition>
            </span>
          </Button>
        </CardContent>
      </Card>
    </transition>
  </div>

  <!-- Results Stage -->
  <div v-else-if="stage === 'results'" class="max-w-2xl mx-auto">
    <transition appear name="fade">
      <Card class="bg-white/90 backdrop-blur-sm border-pink-200 shadow-xl">
        <CardHeader class="text-center pb-6">
          <div
            class="w-20 h-20 bg-gradient-to-br from-pink-600 to-rose-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
          >
            <Trophy class="w-10 h-10 text-white" />
          </div>
          <CardTitle class="text-3xl text-slate-800 mb-2">{{ t('emotionRecognitionTest.testComplete') }}</CardTitle>
          <div
            class="text-6xl font-bold bg-gradient-to-r from-pink-600 to-rose-500 bg-clip-text text-transparent"
          >
            {{ results.accuracy }}
          </div>
          <p class="text-slate-600">{{ t('emotionRecognitionTest.accuracy') }}</p>
        </CardHeader>
        <CardContent class="space-y-6">
          <div class="grid grid-cols-3 gap-4">
            <div
              class="text-center p-4 bg-gradient-to-br from-pink-50 to-pink-100 rounded-xl border border-pink-200"
            >
              <div class="text-2xl font-bold text-pink-600 mb-1">
                {{ results.correctAnswers }}/{{ results.totalStimuli }}
              </div>
              <div class="text-sm text-pink-700">{{ t('emotionRecognitionTest.correctlyIdentified') }}</div>
            </div>
            <div
              class="text-center p-4 bg-gradient-to-br from-rose-50 to-rose-100 rounded-xl border border-rose-200"
            >
              <div class="text-2xl font-bold text-rose-600 mb-1">
                {{ results.averageConfidence }}
              </div>
              <div class="text-sm text-rose-700">{{ t('emotionRecognitionTest.averageConfidence') }}</div>
            </div>
            <div
              class="text-center p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl border border-purple-200"
            >
              <div class="text-2xl font-bold text-purple-600 mb-1">
                {{ results.averageReactionTime }}s
              </div>
              <div class="text-sm text-purple-700">{{ t('emotionRecognitionTest.averageReaction') }}</div>
            </div>
          </div>
          <Button
            class="w-full bg-gradient-to-r from-pink-600 to-rose-500 hover:from-pink-700 hover:to-rose-600 text-white py-3 text-lg font-semibold shadow-lg"
            size="lg"
            @click="handleComplete"
          >
            {{ t('emotionRecognitionTest.viewDetailedResults') }}
          </Button>
        </CardContent>
      </Card>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import {
  Heart,
  Clock,
  Trophy,
  Star,
  Eye,
  Users,
  Mic,
  Smile,
} from "lucide-vue-next";
import {
  EMOTION_SCENARIOS,
  EMOTION_CATEGORIES,
  EMOTION_NAMES,
  CONTEXT_DESCRIPTIONS,
} from "../constants/emotionRecognition";
import { useGlobalI18n } from '~/composables/useGlobalI18n';

const { t } = useGlobalI18n();

const emit = defineEmits(["complete"]);

// --- State ---
const stage = ref("instructions"); // 'instructions', 'test', 'confidence', 'results'
const currentStimulus = ref(0);
const selectedStimuli = ref([]);
const selectedEmotion = ref("");
const confidence = ref([3]);
const responses = ref([]);
const startTime = ref(0);
const stimulusStartTime = ref(0);
const score = ref(0);
const showFeedback = ref(false);
const feedbackCorrect = ref(false);
const feedbackMessage = ref("");
const isSubmitting = ref(false);

const TOTAL_STIMULI = 15;

// --- Computed Properties ---
const currentStimulusData = computed(
  () => selectedStimuli.value[currentStimulus.value]
);
const progress = computed(() =>
  selectedStimuli.value.length > 0
    ? (currentStimulus.value / selectedStimuli.value.length) * 100
    : 0
);

const stimulusTypeDescription = computed(
  () => CONTEXT_DESCRIPTIONS[currentStimulusData.value?.type] || ""
);
const stimulusTypeClass = computed(() => {
  if (!currentStimulusData.value) return "";
  switch (currentStimulusData.value.type) {
    case "facial_expression":
      return "bg-blue-100 text-blue-700 border-blue-300";
    case "body_language":
      return "bg-green-100 text-green-700 border-green-300";
    case "voice_tone":
      return "bg-purple-100 text-purple-700 border-purple-300";
    case "social_scenario":
      return "bg-orange-100 text-orange-700 border-orange-300";
    default:
      return "bg-red-100 text-red-700 border-red-300";
  }
});

const stimulusDifficultyDescription = computed(() => {
  if (!currentStimulusData.value) return "";
  switch (currentStimulusData.value.difficulty) {
    case "easy":
      return t('emotionRecognitionTest.difficultyEasy');
    case "medium":
      return t('emotionRecognitionTest.difficultyMedium');
    case "hard":
      return t('emotionRecognitionTest.difficultyHard');
    default:
      return "";
  }
});

const stimulusDifficultyClass = computed(() => {
  if (!currentStimulusData.value) return "";
  switch (currentStimulusData.value.difficulty) {
    case "easy":
      return "bg-green-100 text-green-700 border-green-300";
    case "medium":
      return "bg-yellow-100 text-yellow-700 border-yellow-300";
    case "hard":
      return "bg-red-100 text-red-700 border-red-300";
    default:
      return "";
  }
});

const intensityDescription = computed(() => {
  if (!currentStimulusData.value) return "";
  switch (currentStimulusData.value.intensity) {
    case "low":
      return t('emotionRecognitionTest.intensityLow');
    case "medium":
      return t('emotionRecognitionTest.intensityMedium');
    case "high":
      return t('emotionRecognitionTest.intensityHigh');
    default:
      return "";
  }
});

const confidenceDescription = computed(() => {
  switch (confidence.value[0]) {
    case 1:
      return t('emotionRecognitionTest.confidenceLevel1');
    case 2:
      return t('emotionRecognitionTest.confidenceLevel2');
    case 3:
      return t('emotionRecognitionTest.confidenceLevel3');
    case 4:
      return t('emotionRecognitionTest.confidenceLevel4');
    case 5:
      return t('emotionRecognitionTest.confidenceLevel5');
    default:
      return "";
  }
});

const results = computed(() => {
  if (stage.value !== "results") return {};
  const total = selectedStimuli.value.length;
  const correct = score.value;
  const accuracy = total > 0 ? Math.round((correct / total) * 100) : 0;
  const avgConfidence =
    responses.value.length > 0
      ? Math.round(
          (responses.value.reduce((sum, r) => sum + r.confidence, 0) /
            responses.value.length) *
            10
        ) / 10
      : 0;
  const avgReactionTime =
    responses.value.length > 0
      ? Math.round(
          responses.value.reduce((sum, r) => sum + r.reactionTime, 0) /
            responses.value.length /
            1000
        )
      : 0;
  return {
    accuracy,
    correctAnswers: correct,
    totalStimuli: total,
    averageConfidence: avgConfidence,
    averageReactionTime: avgReactionTime,
  };
});

// --- Methods ---
onMounted(() => {
  // Pre-shuffle stimuli on mount
  const stimuli = selectStimuli();
  selectedStimuli.value = stimuli;
});

const selectStimuli = () => {
  const shuffled = [...EMOTION_SCENARIOS].sort(() => Math.random() - 0.5);
  const stimuliByType = {
    facial_expression: [],
    body_language: [],
    voice_tone: [],
    social_scenario: [],
    micro_expression: [],
  };

  shuffled.forEach((stimulus) => {
    if (stimuliByType[stimulus.type].length < 3) {
      stimuliByType[stimulus.type].push(stimulus);
    }
  });

  const selected = Object.values(stimuliByType).flat();

  if (selected.length < TOTAL_STIMULI) {
    const remaining = shuffled.filter(
      (s) => !selected.find((sel) => sel.id === s.id)
    );
    const difficultyBalance = {
      easy: Math.ceil((TOTAL_STIMULI - selected.length) * 0.4),
      medium: Math.ceil((TOTAL_STIMULI - selected.length) * 0.4),
      hard: Math.floor((TOTAL_STIMULI - selected.length) * 0.2),
    };

    ["easy", "medium", "hard"].forEach((difficulty) => {
      const diffItems = remaining.filter((s) => s.difficulty === difficulty);
      selected.push(...diffItems.slice(0, difficultyBalance[difficulty]));
    });
  }

  return selected
    .slice(0, TOTAL_STIMULI)
    .map((stimulus) => ({
      ...stimulus,
      options: [...stimulus.options].sort(() => Math.random() - 0.5),
    }))
    .sort(() => Math.random() - 0.5);
};

const handleStartTest = () => {
  stage.value = "test";
  startTime.value = Date.now();
  stimulusStartTime.value = Date.now();
};

const handleEmotionSelect = (emotion) => {
  selectedEmotion.value = emotion;
  stage.value = "confidence";
};

const handleConfidenceSubmit = () => {
  if (!selectedEmotion.value || isSubmitting.value) return;

  isSubmitting.value = true;

  const stimulus = currentStimulusData.value;
  const reactionTime = Date.now() - stimulusStartTime.value;
  const correctEmotion = EMOTION_NAMES[stimulus.emotion];
  const isCorrect = selectedEmotion.value === correctEmotion;

  responses.value.push({
    stimulusId: stimulus.id,
    selectedEmotion: selectedEmotion.value,
    correct: isCorrect,
    reactionTime,
    confidence: confidence.value[0],
    stimulusType: stimulus.type,
    difficulty: stimulus.difficulty,
  });

  if (isCorrect) {
    score.value++;
  }

  stage.value = "test";
  feedbackCorrect.value = isCorrect;
  feedbackMessage.value = isCorrect
    ? t('emotionRecognitionTest.feedbackCorrectMessage', { emotion: correctEmotion })
    : t('emotionRecognitionTest.feedbackIncorrectMessage', { correctEmotion: correctEmotion, selectedEmotion: selectedEmotion.value });
  showFeedback.value = true;

  setTimeout(() => {
    showFeedback.value = false;
    selectedEmotion.value = "";
    confidence.value = [3];
    isSubmitting.value = false;

    if (currentStimulus.value < selectedStimuli.value.length - 1) {
      currentStimulus.value++;
      stimulusStartTime.value = Date.now();
    } else {
      stage.value = "results";
    }
  }, 1200);
};

const analyzeConfusionMatrix = (res) => {
  const matrix = {};
  res.forEach((response) => {
    const stimulus = selectedStimuli.value.find(
      (s) => s.id === response.stimulusId
    );
    if (!stimulus) return;
    const actual = EMOTION_NAMES[stimulus.emotion];
    const predicted = response.selectedEmotion;
    if (!matrix[actual]) matrix[actual] = {};
    if (!matrix[actual][predicted]) matrix[actual][predicted] = 0;
    matrix[actual][predicted]++;
  });
  return matrix;
};

const analyzeTypeAccuracy = (res) => {
  const typeStats = {};
  res.forEach((response) => {
    const stimulus = selectedStimuli.value.find(
      (s) => s.id === response.stimulusId
    );
    if (!stimulus) return;
    const type = CONTEXT_DESCRIPTIONS[stimulus.type];
    if (!typeStats[type]) typeStats[type] = { correct: 0, total: 0 };
    typeStats[type].total++;
    if (response.correct) typeStats[type].correct++;
  });
  const result = {};
  Object.entries(typeStats).forEach(([type, stats]) => {
    result[type] = stats.total > 0 ? (stats.correct / stats.total) * 100 : 0;
  });
  return result;
};

const handleComplete = () => {
  const res = responses.value;
  const analysis = {
    overallAccuracy: results.value.accuracy,
    basicEmotionAccuracy: 0,
    complexEmotionAccuracy: 0,
    microExpressionAccuracy: 0,
    averageReactionTime: results.value.averageReactionTime,
    averageConfidence: results.value.averageConfidence,
    emotionConfusionMatrix: analyzeConfusionMatrix(res),
    strengthsByType: analyzeTypeAccuracy(res),
  };

  emit("complete", {
    id: Date.now().toString(),
    testType: "emotion-recognition",
    score: results.value.accuracy,
    completedAt: new Date(),
    duration: Math.round((Date.now() - startTime.value) / 1000),
    details: { ...results.value, ...analysis },
  });
};
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.slide-down-enter-active,
.slide-down-leave-active {
  transition: all 0.5s ease;
}

.slide-down-enter-from,
.slide-down-leave-to {
  opacity: 0;
  transform: translateY(-20px);
}

.animate-spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>